import { ref } from "vue"
import store from "@/store"
import { defineStore } from "pinia"
import { type RouteRecordRaw } from "vue-router"
import { constantRoutes, asyncRoutes } from "@/router"
import { flatMultiLevelRoutes } from "@/router/helper"
import routeSettings from "@/config/route"
import { getRoutersApi } from '@/api/login'
import { getPermissionsBtns } from "@/utils/cache/local-storage"

const hasPermission = (roles: string[], route: RouteRecordRaw) => {
  const routeRoles = route.meta?.roles
  return routeRoles ? roles.some((role) => routeRoles.includes(role)) : true
}

const filterAsyncRoutes = (routes: RouteRecordRaw[], roles: string[]) => {
  const res: RouteRecordRaw[] = []
  routes.forEach((route) => {
    const tempRoute = { ...route }

    if (tempRoute.children) {
      tempRoute.children = filterAsyncRoutes(tempRoute.children, roles)
    }
    res.push(tempRoute)
    // if (hasPermission(roles, tempRoute)) {

    // }
  })

  return res
}

export const usePermissionStore = defineStore("permission", () => {
  const routes = ref<RouteRecordRaw[]>([])
  const dynamicRoutes = ref<RouteRecordRaw[]>([])
  const permissionsBtns = ref([])
  const setRoutes = async (roles: string[] = []) => {
    let asyncRoutesNew = []
    if (routeSettings.async) asyncRoutesNew = await getRoutersInfo()
     asyncRoutesNew.push(...asyncRoutes)
    const accessedRoutes = routeSettings.async ? filterAsyncRoutes(asyncRoutesNew, roles) : asyncRoutesNew
    routes.value = constantRoutes.concat(accessedRoutes)
    dynamicRoutes.value = routeSettings.thirdLevelRouteCache ? flatMultiLevelRoutes(accessedRoutes) : accessedRoutes
    console.log('最终路由', dynamicRoutes.value);
    permissionsBtns.value = getPermissionsBtns()  //获取缓存按钮
  }

  // 获取动态路由
  const getRoutersInfo = async () => {
    let res = await getRoutersApi()
    console.log('后端返回', res.data);
    return  convertMenuToRoutesWithNesting(res.data);
  }

  /**
* 自动扫描views文件夹下的Vue文件，生成路由映射
*/
  const autoGenerateRouteMap = () => {
    const routeMap = {};

    // 使用Vite的glob功能扫描所有Vue文件
    const modules = import.meta.glob('@/views/**/index.vue', { eager: false });

    Object.keys(modules).forEach(filePath => {
      // 转换文件路径为路由路径
      const routePath = convertFilePathToRoutePath(filePath);
      routeMap[routePath] = modules[filePath];
    });

    return routeMap;
  }
  /**
 * 将文件路径转换为路由路径
 * 例如: src/views//system/user/index.vue -> //system/user
 */
  function convertFilePathToRoutePath(filePath) {
    // 移除前缀和后缀
    let path = filePath
      .replace('/src/views', '')
      .replace('/index.vue', '')
      .replace('.vue', '');

    // 处理空路径（首页情况）
    if (path === '' || path === '/') {
      return '/';
    }

    return path;
  }

  /**
 * 根据路径获取组件（支持无限层级）
 */
  function getDynamicComponent(path) {
    const routeMap = autoGenerateRouteMap();
    // 精确匹配
    if (routeMap[path]) {
      return routeMap[path];
    }

    // 处理带参数的路由（如 /user/:id）
    if (path.includes(':')) {
      const basePath = path.split('/:')[0];
      if (routeMap[basePath]) {
        return routeMap[basePath];
      }
    }

    console.warn(`未找到路径 ${path} 对应的组件`);
    return false;
  }

  /**
   * 增强版路由转换，支持无限层级嵌套
   * 返回符合Vue Router格式的嵌套路由结构
   */
  function convertMenuToRoutesWithNesting(menuData, parentPath = '') {
    const Layouts = () => import("@/layouts/index.vue")
    const traverse = (menus, currentParentPath = '') => {
      const currentLevelRoutes = []; // 当前层级的路由
      for (const menu of menus) {
        // 跳过隐藏菜单
        if (menu.hidden) {
          continue;
        }

        // 处理路径拼接
        let menuPath = menu.path || '';
        if (menuPath && !menuPath.startsWith('/')) {
          menuPath = '/' + menuPath;
        }

        // let arr= menuPath.split('/')
        // let fullPath = currentParentPath + menuPath;
        // if(arr.length==3)fullPath=menuPath


        const fullPath = menuPath;

        // 处理目录类型（M）- 作为父路由
        if (menu.menuType === 'M') {
          const route = {
            path: fullPath || '/',
            name: menu.menuCode || `menu_${menu.menuId}`,
            component: currentParentPath ? null : Layouts,
            meta: {
              id: menu.menuId,
              title: menu.menuName,
              // code: menu.menuCode,
              icon: menu.icon,
              hidden: menu.hidden,
              menuType: menu.menuType,
            },
            redirect: ''
            // 先不添加children，等确定有子路由再添加
          };
          console.log('route', route);

          // 递归处理子菜单
          if (menu.children && menu.children.length > 0) {
            const childRoutes = traverse(menu.children, fullPath);
            // 只有当有有效的子路由时才添加children
            if (childRoutes.length > 0) {
              route.children = childRoutes;
              route.redirect = childRoutes[0].path;
            }
          }

          // 只有有子菜单的目录才添加到路由
          if (route.children && route.children.length > 0) {
            currentLevelRoutes.push(route);
          }
          continue;
        }

        // 处理菜单类型（C）- 作为叶子路由
        if (menu.menuType === 'C' && fullPath) {
          const route = {
            path: fullPath, // 使用相对路径
            name: menu.menuCode || `menu_${menu.menuId}`,
            meta: {
              id: menu.menuId,
              title: menu.menuName,
              // code: menu.menuCode,
              icon: menu.icon,
              hidden: menu.hidden,
              menuType: menu.menuType,
            },
            component: getDynamicComponent(fullPath)
            // 不默认添加children
          };

          // 只有在有子菜单且子菜单包含有效路由时才添加children
          if (menu.children && menu.children.length > 0) {
            const childRoutes = traverse(menu.children, fullPath);
            if (childRoutes.length > 0) {
              route.children = childRoutes;
            }
          }
          if (route.component) currentLevelRoutes.push(route);
        }
      }

      return currentLevelRoutes;
    };

    const resultRoutes = traverse(menuData, parentPath);

    return resultRoutes
  }

  // 验证按钮是否有权限
  const isPermissionsBtn = (val) => {
    // 如果没有权限列表，直接返回false
    if (!permissionsBtns.value || !permissionsBtns.value.length) {
      return false;
    }

    // 如果val是数组，检查是否至少有一个权限存在
    if (Array.isArray(val)) {
      return val.some(permission => permissionsBtns.value.includes(permission));
    }

    // 如果val是字符串，检查单个权限
    if (typeof val === 'string') {
      return permissionsBtns.value.includes(val);
    }

    // 其他情况返回false
    return false;
  }

  return { routes, dynamicRoutes, permissionsBtns, setRoutes, isPermissionsBtn }
})

/** 在 setup 外使用 */
export function usePermissionStoreHook() {
  return usePermissionStore(store)
}
